<script setup lang="ts">
import {message} from 'ant-design-vue';
import {useForm, useModal} from '#/ui-kit';
import {useDictStore} from '#/stores';

import {createParameterInfo, updateParameterInfo} from "#/api/system/parameter";

const emits = defineEmits(['close']);

const {getDictData} = useDictStore();

const [Modal, modalApi] = useModal({
  draggable: true,
  closeOnClickModal: false,
  destroyOnClose: true,
  onConfirm: function () {
    formApi.validateAndSubmitForm();
  },
  onBeforeClose: function () {
    modalApi.setState({confirmLoading: false})
    modalApi.setData({});
    formApi.resetForm();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      formApi.setValues(modalApi.getData(), false, false);
    }
  }
});

const [Form, formApi] = useForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
      allowClear: true,
    },
  },
  layout: 'horizontal',
  showDefaultActions: false,
  schema: [
    {
      label: '参数名称',
      fieldName: 'name',
      component: 'Input',
      componentProps: {placeholder: '请输入参数名称'},
      rules: 'required',
    },
    {
      label: '参数键名',
      fieldName: 'key',
      component: 'Input',
      componentProps: {placeholder: '请输入参数键名'},
      rules: 'required',
    },
    {
      label: '参数键值',
      fieldName: 'value',
      component: 'Textarea',
      componentProps: {placeholder: '请输入参数键值'},
      rules: 'required',
    },
    {
      label: '备注',
      fieldName: 'remark',
      component: 'Textarea',
      componentProps: {placeholder: '请输入备注'},
    },
    {
      label: '启用状态',
      fieldName: 'enableStatus',
      component: 'RadioGroup',
      componentProps: {
        options: getDictData('enable_status', true),
      },
      defaultValue: 0,
    },
  ],
  handleSubmit: function (values) {
    modalApi.setState({confirmLoading: true})
    if (values?.id) {
      updateParameterInfo(values).then(() => {
        message.success('参数信息更新成功');
        modalApi.close();

        emits('close');
      }).finally(() => {
        modalApi.setState({confirmLoading: false})
      });
    } else {
      createParameterInfo(values).then(() => {
        message.success('参数信息新增成功');
        modalApi.close();

        emits('close');
      }).finally(() => {
        modalApi.setState({confirmLoading: false})
      });
    }
  }
});
</script>

<template>
  <Modal>
    <Form/>
  </Modal>
</template>